const errorTypes = require('../error/error-types')
const userService = require('../service/user.service')
const momentService = require('../service/moment.service')
const md5password = require("../utils/password")
const { PUBLIC_KEY } = require('../app/config')
const jwt = require('jsonwebtoken')
const wrapper = require('../wrapper')

// 登录校验
const verifyLogin = async (ctx, next) => {
  // 1.获取用户名、密码
  const { nickname, password } = ctx.request.body
  // 2.判断用户名、密码不为空
  if (!nickname || !password) {
    const error = new Error(errorTypes.NICKNAME_OR_PASSWORD_IS_REQUIRED)
    return ctx.app.emit('error', error, ctx)
  }
  // 3.判断用户是否存在
  const result = await userService.getUserByNickname(nickname)
  // @ts-ignore
  if (result.length === 0) {
    const error = new Error(errorTypes.USER_DOES_NOT_EXISTS)
    return ctx.app.emit('error', error, ctx)
  }
  // 4.判断密码是否正确
  if (md5password(password) !== result[0].password) {
    const error = new Error(errorTypes.PASSWORD_IS_INCORRENT)
    return ctx.app.emit('error', error, ctx)
  }

  ctx.user = result[0]  // 保存用户
  // 5.进行下一步
  await next()
}


// 验证token是否有效
const verifyAuth = async (ctx, next) => {
  // 1.获取token
  const authorization = ctx.headers.authorization
  if (!authorization) {
    // 没有传token
    const error = new Error(errorTypes.UN_AUTHORIZED)
    return ctx.app.emit('error', error, ctx)
  }
  const token = authorization.replace("Bearer ", "")

  // 2.验证token
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"]
    })
    ctx.user = result
    await next()
  } catch (err) {
    // 错误/过期的token
    const error = new Error(errorTypes.UN_AUTHORIZED)
    ctx.app.emit('error', error, ctx)
  }
}

// 验证动态权限
const verifyMoment = async (ctx, next) => {
  try {
    const { momentId } = ctx.query
    const { id } = ctx.user
    const result = await momentService.getMomentByIdAndUserId(momentId, id)
    if (!result.id) {
      ctx.body = wrapper.wrapTo500(null, "没有操作权限")
    }
    await next()
  } catch (err) {
    const error = new Error(errorTypes.UN_AUTHORIZED)
    ctx.app.emit('error', error, ctx)
  }
}

module.exports = {
  verifyLogin,
  verifyAuth,
  verifyMoment
}
